#!/bin/sh

. /lib/functions.sh

uci_find_swap() {
	local swap_dev device
	device="$2"
	config_get swap_dev "$1" device
	[ "$swap_dev" = "/dev/$device" ] && skip_flag=1
}

uci_find_uuid() {
	local uuid dev_uuid
	config_get uuid "$1" uuid
	dev_uuid="$2"
	[ "$uuid" = "$dev_uuid" ] && skip_flag=1
}

mkdir_for_mnt_point() {
	local uuid target_dir dev_uuid
	config_get uuid "$1" uuid
	dev_uuid="$2"
	[ "$uuid" = "$dev_uuid" ] && {
		config_get target_dir "$1" target
		[ -n "$target_dir" ] && {
			[ -d "$target_dir" ] ||
				mkdir -m 777 -p "$target_dir"
		}
	}
}

set_mount() {
	local skip_flag mnt_opts dev_uuid fstype device new_mount new_swap

	device="$1"
	[ -n "$device" ] || return 1

	fstype="$(lsblk -n -o FSTYPE "/dev/${device}")"
	[ -n "$fstype" ] || return 1

	logger -t Auto-Mount "Block detected, file system: ${fstype}."

	skip_flag=0

	if [ "$fstype" = 'swap' ]; then
		config_load fstab
		config_foreach uci_find_swap swap "$device"
		[ $skip_flag -eq 0 ] && {
			new_swap=$(uci add fstab swap)
			uci -q batch <<-EOI
				set fstab.$new_swap.enabled=1
				set fstab.$new_swap.device="/dev/$device"
				commit fstab
			EOI
		}
	else
		dev_uuid="$(lsblk -n -o UUID "/dev/${device}")"
		[ -n "$dev_uuid" ] && {
			config_load fstab
			config_foreach uci_find_uuid mount "$dev_uuid"

			[ $skip_flag -eq 0 ] ||
				logger -t Auto-Mount "Block with UUID $dev_uuid already exists."

			mnt_opts=
			[ $skip_flag -eq 0 ] && {
				case "$fstype" in
				'ext2' | 'ext3' | 'ext4')
					mnt_opts="noatime"
					;;
				'ntfs')
					fstype="ntfs-3g"
					mnt_opts="noatime,iocharset=utf8,big_writes"
					;;
				'exfat')
					mnt_opts="noatime"
					;;
				'vfat')
					mnt_opts="iocharset=utf8,umask=0000,dmask=0000,fmask=0000"
					;;
				*)
					skip_flag=1
					logger -t Auto-Mount "File system: ${fstype} not supported."
					;;
				esac
			}

			[ $skip_flag -eq 0 ] && {
				logger -t Auto-Mount "New block /dev/${device} added."
				logger -t Auto-Mount "UUID=$dev_uuid"
				new_mount=$(uci add fstab mount)
				uci -q batch <<-EOI
					set fstab.$new_mount.enabled=1
					set fstab.$new_mount.uuid="$dev_uuid"
					set fstab.$new_mount.target="/tmp/mnt/$device"
					set fstab.$new_mount.fstype="$fstype"
					set fstab.$new_mount.options="$mnt_opts"
					commit fstab
				EOI
			}

			config_load fstab
			config_foreach mkdir_for_mnt_point mount "$dev_uuid"
		}
	fi
}

[ "$DEVTYPE" = "partition" ] || exit

device="$DEVNAME"
case "$device" in
sd*) ;;
md*) ;;
hd*) ;;
mmcblk*) ;;
*) exit ;;
esac

mkdir -p /var/lock
lock /var/lock/automount.lock

case "$ACTION" in
add)
	set_mount "$device"
	;;

remove)
	grep "^/dev/${device}[[:space:]]\+" /proc/mounts |
		awk '{print $2}' | sort -u |
		while read -r mountpoint; do
			/bin/force-unmount "$mountpoint" >/dev/null 2>&1
		done

	grep -q "^/dev/${device}[[:space:]]\+" /proc/swaps &&
		swapoff "/dev/$device" >/dev/null 2>&1
	;;
esac

lock -u /var/lock/automount.lock
